<template>
  <div class="container">
    <Breadcrumb
      :items="[$t('menu.part.production'), $t('menu.part.platemodule')]"
    />

    <a-card class="general-card">
      <template #title>
        <span>选择序列</span>
        <a-tree-select
          :data="datatree"
          v-model="formModel.selected"
          placeholder="Please select ..."
          style="width: 300px"
          @change="onChange"
        >
        </a-tree-select>

        <a-space>
          <a-button @click="handleClick" type="primary">添加零件分类</a-button>
          <a-modal
            v-model:visible="visiblePart"
            title="添加零件分类"
            @cancel="handleCancel"
            @before-ok="handleBeforeOk"
          >
            <a-form :model="formPart">
              <a-form-item field="pid" label="上级零件">
                <a-tree-select
                  v-model="formPart.pid"
                  :data="renderDataPart"
                  placeholder="请选择上级零件"
                />
              </a-form-item>
              <a-form-item field="name" label="零件名称">
                <a-input v-model="formPart.name" />
              </a-form-item>
            </a-form>
          </a-modal>
        </a-space>

        <a-space>
          <a-button @click="handleClickEdit" type="primary"
            >编辑零件分类</a-button
          >
          <a-modal
            v-model:visible="visiblePartEdit"
            title="编辑零件分类"
            @cancel="handleCancelEdit"
            @before-ok="handleBeforeOkEdit"
          >
            <a-form :model="formPartEdit">
              <a-form-item field="id" label="上级零件">
                <a-tree-select
                  v-model="formPartEdit.id"
                  :data="renderDataPartEdit"
                  placeholder="请选择上级零件"
                />
              </a-form-item>
              <a-form-item field="name" label="零件名称">
                <a-input v-model="formPartEdit.name" />
              </a-form-item>
            </a-form>
          </a-modal>
        </a-space>

        <a-space>
          <a-button @click="handleClickDelete" type="primary"
            >删除零件分类</a-button
          >
          <a-modal
            v-model:visible="visiblePartDelete"
            title="删除零件分类"
            @cancel="handleCancelDelete"
            @before-ok="handleBeforeOkDelete"
          >
            <a-form :model="formPartDelete">
              <a-form-item field="id" label="上级零件">
                <a-tree-select
                  v-model="formPartDelete.id"
                  :data="renderDataPartDelete"
                  placeholder="请选择上级零件"
                />
              </a-form-item>
            </a-form>
          </a-modal>
        </a-space>
      </template>

      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="add">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>

            <!-- <a-upload action="/">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload> -->
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <!-- <a-button>
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button> -->
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderDataPartList"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #contentType="{ record }">
          <a-space>
            <a-avatar
              v-if="record.contentType === 'img'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/581b17753093199839f2e327e726b157.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar
              v-else-if="record.contentType === 'horizontalVideo'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/77721e365eb2ab786c889682cbc721c1.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar v-else :size="16" shape="square">
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/ea8b09190046da0ea7e070d83c5d1731.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            {{ $t(`searchTable.form.contentType.${record.contentType}`) }}
          </a-space>
        </template>
        <template #filterType="{ record }">
          {{ $t(`searchTable.form.filterType.${record.filterType}`) }}
        </template>
        <template #status="{ record }">
          <span v-if="record.status === 'offline'" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ $t(`searchTable.form.status.${record.status}`) }}
        </template>
        <template #optional="{ record }">
          <a-button type="text" size="small" @click="edit(record)">
            <template #icon>
              <icon-edit />
            </template>
            编辑
          </a-button>
          <a-popconfirm
            :content="`此操作将永久删除(${record.name}), 是否继续?`"
            type="warning"
            @ok="delPart(record)"
          >
            <a-button type="text" size="small" status="danger">
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <MenuForm
      v-model:visible="formDialogVisible"
      :form-data="formData"
      :selected="selectedKey"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
  import { FieldRule, Message } from '@arco-design/web-vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { PolicyRecord, PolicyParams, Pagination } from '@/api/part';

  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  import MenuForm from './components/menu-form.vue';
  import {
    addPartCat,
    deletePartCat,
    delPartInfo,
    editPartCat,
    getAllPartList,
    partAddNumber,
    queryPartList,
  } from '@/api/part';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      selected: '插座',
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const generateFormAdd = () => {
    return {
      selected: '',
      name: '',
      age: undefined,
      section: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderDataPartList = ref([]);
  const formModel = ref(generateFormModel());
  const formAdd = ref(generateFormAdd());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);
  const datatree = ref([]);

  //加库存
  const visibleAddNumber = ref(false);
  const AddNumber = ref();
  const handleClickAddNumber = () => {
    visibleAddNumber.value = true;
  };
  const handleOkAddNumber = async (data: any) => {
    console.log(data);
    console.log(AddNumber.value);
    if (AddNumber.value > 0) {
      const datainfo = {
        id: data.id,
        number: AddNumber.value,
      };
      console.log(datainfo);
      await partAddNumber(datainfo).then(() => {
        Message.success('添加库存成功');
      });
    } else {
      Message.error('请输入大于0的数字');
    }

    visibleAddNumber.value = false;
  };
  const handleCancelAddNumber = () => {
    visibleAddNumber.value = false;
  };
  //减库存
  const visibleSubtractNumber = ref(false);
  const SubtractNumber = ref();
  const handleClickSubtractNumber = () => {
    visibleSubtractNumber.value = true;
  };
  const handleOkSubtractNumber = async (data: any) => {
    console.log(data);
    console.log(SubtractNumber.value);
    if (SubtractNumber.value > 0) {
      const datainfo = {
        id: data.id,
        number: '-' + SubtractNumber.value,
      };
      console.log(datainfo);
      await partAddNumber(datainfo).then(() => {
        Message.success('减少库存成功');
      });
    } else {
      Message.error('请输入大于0的数字');
    }
    visibleSubtractNumber.value = false;
  };
  const handleCancelSubtractNumber = () => {
    visibleSubtractNumber.value = false;
  };

  //树选择
  onMounted(async () => {
    const Data = await getAllPartList();
    datatree.value = changePart(Data.data);
    console.log('datatree', datatree);
    console.log(Data);
  });
  //零件系列添加对话框
  const visiblePart = ref(false);
  const renderDataPart = ref();
  const formPart = reactive({
    name: '',
    pid: '',
  });
  const handleClick = () => {
    visiblePart.value = true;

    console.log(datatree.value[0].key);
    if (datatree.value[0].key != 0) {
      datatree.value.splice(0, 0, {
        key: '0',
        pid: '0',
        title: '创建一级标准件系列',
      });
    }

    console.log(datatree.value);

    renderDataPart.value = datatree.value;
    console.log(renderDataPart);
  };
  const handleBeforeOk = async (done) => {
    console.log(formPart);
    await addPartCat(formPart).then(() => {
      Message.success('添加零件分类成功');
    });
    window.setTimeout(() => {
      done();
      // prevent close
      // done(false)
    }, 3000);
  };
  const handleCancel = () => {
    visiblePart.value = false;
  };

  //零件系列编辑对话框
  const visiblePartEdit = ref(false);
  const renderDataPartEdit = ref();
  const formPartEdit = reactive({
    name: '',
    id: '',
  });
  const handleClickEdit = () => {
    visiblePartEdit.value = true;
    renderDataPartEdit.value = datatree.value;
    console.log(renderDataPartEdit);
  };
  const handleBeforeOkEdit = async (done) => {
    console.log(formPartEdit);
    await editPartCat(formPartEdit).then(() => {
      Message.success('编辑零件分类成功');
    });
    window.setTimeout(() => {
      done();
      // prevent close
      // done(false)
    }, 3000);
  };
  const handleCancelEdit = () => {
    visiblePartEdit.value = false;
  };

  //零件系列删除对话框
  const visiblePartDelete = ref(false);
  const renderDataPartDelete = ref();
  const formPartDelete = reactive({
    id: '',
  });
  const handleClickDelete = () => {
    visiblePartDelete.value = true;
    renderDataPartDelete.value = datatree.value;
    console.log(renderDataPartDelete);
  };
  const handleBeforeOkDelete = async (done) => {
   
    await deletePartCat(formPartDelete).then(() => {
      Message.success('删除零件分类成功');
    });
    window.setTimeout(() => {
      done();
      // prevent close
      // done(false)
    }, 3000);
  };
  const handleCancelDelete = () => {
    visiblePartDelete.value = false;
  };
  const treeData = [
    {
      title: 'Trunk 0-0',
      key: '0-0',
      children: [
        {
          title: 'Branch 0-0-0',
          key: '0-0-0',
          children: [
            {
              title: 'Leaf',
              key: '0-0-0-0',
            },
            {
              title: 'Leaf',
              key: '0-0-0-1',
            },
          ],
        },
        {
          title: 'Branch 0-0-1',
          key: '0-0-1',
          children: [
            {
              title: 'Leaf',
              key: '0-0-1-0',
            },
          ],
        },
      ],
    },
  ];

  //编辑添加按钮
  const formData = ref();

  // 弹出框标记
  const formDialogVisible = ref(false);
  const add = () => {
    const arr = selectedKeyData(datatree.value);

    if (arr.pid == 0) {
      console.log(arr.pid);
      Message.error('请选择二级分类');
    } else {
      formData.value = {};
      formDialogVisible.value = true;
    }
  };

  const selectedKeyData = (data) => {
    for (const item of data) {
      if (item.key == selectedKey.value) {
        console.log(item);
        return item;
      }
      if (item.children != null && item.children.length !== 0) {
        const result = selectedKeyData(item.children);
        if (result != null) {
          return result;
        }
      }
    }
  };

  const edit = (e: any) => {
    formDialogVisible.value = true;

    formData.value = { ...e };
  };

  const size = ref<SizeProps>('medium');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    selected: 1,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: 'id',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '零件名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '材质',
      dataIndex: 'material',
      align: 'center',
    },
    {
      title: '加工性质',
      dataIndex: 'process_type',
      align: 'center',
    },
    {
      title: '对外报价',
      dataIndex: 'external_price',
      align: 'center',
    },
    {
      title: '库存',
      dataIndex: 'stock',
      align: 'center',
    },
    {
      title: '机器预约数',
      dataIndex: 'book_stock',
      align: 'center',
    },
    {
      title: '成本价',
      dataIndex: 'cost_price',
      align: 'center',
    },
    {
      title: '购买地址',
      dataIndex: 'buy_address',
      align: 'center',
    },
    {
      title: '是否售后配件',
      dataIndex: 'is_aftersale_part',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '零件一级分类',
      dataIndex: 'cat_name',
      align: 'center',
    },
    {
      title: '零件一级分类',
      dataIndex: 'cat_second_name',
      align: 'center',
    },

    {
      title: '操作',
      slotName: 'optional',
      align: 'center',
    },
  ]);



  const fetchData = async (
    params = { current: 1, pageSize: 10, selected: 1, isSecond: 1 }
  ) => {
    setLoading(true);
    try {
   
      const { data } = await queryPartList(params);

      renderDataPartList.value = dataChinese1(dataChinese(data.data));
 
      pagination.current = 1;
      pagination.total = 10;
    } catch (err) {
   
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const dataChinese = (data) => {
    for (const item of data) {
      if (item.material == 1) {
        item.material = '铝';
      } else if (item.material == 2) {
        item.material = '铜';
      } else if (item.material == 3) {
        item.material = '铁';
      }
    }
    return data;
  };
  const dataChinese1 = (data) => {
    for (const item of data) {
      if (item.process_type == 1) {
        item.process_type = '标准件';
      } else if (item.process_type == 2) {
        item.process_type = '钣金';
      } else if (item.process_type == 3) {
        item.process_type = '机加工';
      } else if (item.process_type == 4) {
        item.process_type = '亚克力';
      }
    }
    return data;
  };

  const selectedKey = ref();
  const text = ref();
  const onChange = (selected: number) => {
   console.log(selected);
   
    text.value = selected;
    selectedKey.value = selected;
    const arr = selectedKeyData(datatree.value);

    let isSecond = null;
    if (arr.pid == 0) {
      isSecond = 0;
    } else {
      isSecond = 1;
    }
   
    fetchData({ ...basePagination, selected, isSecond });
  };
 
  const delPart = async (data: any) => {
    await delPartInfo(data.id).then((res:any) => {
      if(res.code===200) Message.success('删除成功')
      fetchData();
 
    });
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as any);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current }as any);
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );

  function changePart(menuList: any) {
    return menuList?.map((item) => {
      const { id, pid, name } = item;

      const son = item.son ?? [];
      const isChild = son != null && son.length !== 0;
      const currentArray: any = {
        key: id,
        pid: pid,
        title: name,
        children: [],
      };

      if (isChild) {
        currentArray.children = changePart(son);
      }
      return currentArray;
    });
  }
</script>



<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
